<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:26
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-11-13 00:08:02
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Assets\Index.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 单个牧场-打标资产
-->
<script setup lang="ts">
import { reactive, ref, unref } from 'vue'
import { ElButton } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { Asset } from '@/components/VideoPlayer/src/Asset'
// import { LeeSearch } from '@/components/Lee/Search'
import { Table } from '@/components/Table'
import See from './components/See.vue'
import Chat from '@/components/VideoPlayer/src/Asset.vue'
import Edit from './components/Add.vue'

// import { adminFaEarconListApi } from '@/api/fa/earcon'
import { zcAssetEditApi, zcAssetListApi } from '@/api/cy/Assets'
import { sysDictRelsApi } from '@/api/dict'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useTable } from '@/hooks/web/useTableTest'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const dictRelsData = ref() // 联动数据

const breedSubData = ref([]) // 品种的枚举

const searchRef = ref() // 搜索的标签
const iconSee = useIcon({ icon: 'ep:view' })
const iconEdit = useIcon({ icon: 'ep:edit' })

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcAssetListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList, setSearchParams } = methods

// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 70,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code',
    label: '注射编号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    label: '耳标号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: true
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: true
    }
  },
  {
    field: 'sex',
    label: '性别',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.animal_sex
      },
      show: true
    }
  },
  {
    field: 'month_age',
    label: '月龄',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'new_weight',
    label: '重量',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'purchase_date',
    label: '采购日期',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'purchase_price',
    label: '采购价',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'all_purchase_price',
    label: '综合采购价',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'other_fees',
    label: '其他费用',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'is_die',
    label: '是否死亡',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('is', cellValue)
    }
  },
  {
    field: 'enclosure_name',
    label: '栏位',
    width: 150,
    table: {
      show: true
    },
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'purpose',
    label: '用途',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.purpose
      },
      show: true
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 100,
    form: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: 120,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

/****************************** 监听设置固定条件 start ******************************/
// const newFixedSearch = ref({})
// watch(
//   () => tableObject,
//   (val: any) => {
//     if (!val) return
//     // 设置固定条件
//     newFixedSearch.value = {
//       is_die: 0
//     }
//     tableObject.fixedSearch = newFixedSearch.value
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )
/****************************** 监听设置固定条件 start ******************************/

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      Asset(Date.now() > 1706544000000 ? 1 : 2, row.id)
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'assets':
      dialogTitle.value = row.name + '-资产列表'
      // tableObject.currentRow = { ...row, owner_sys_role_id: 2, owner_sys_role_name: '组织管理员' }
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref<any>()
const loading = ref(false)

const save = async () => {
  const edit: any = unref(editRef)

  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const data = (await edit?.getFormData()) as any
          console.log(data, 'dfghj')

          let res = await zcAssetEditApi({
            id: data.id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id ? data.pasture_dept_id : data.pasture_dept_name,
            breed: data.breed,
            breed_sub: data.breed_sub,
            asset_code: data.asset_code,
            asset_code_2: data.asset_code_2,
            earcon_code: data.earcon_code,
            purpose: data.purpose,
            sex: data.sex,
            month_age: data.month_age,
            purchase_price: data.purchase_price,
            all_purchase_price: data.all_purchase_price,
            other_fees: data.other_fees
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
/****************************** 初始化 start ******************************/
const newFixedSearch = ref()
const init = async () => {
  newFixedSearch.value = {
    is_die: '0'
  }
  tableObject.fixedSearch = newFixedSearch.value
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
  console.log('dictRelsData', dictRelsData.value)
}
init()

/****************************** 初始化 end ******************************/
</script>

<template>
  <ContentWrap>
    <!-- <LeeSearch :schema="allSchemas.searchSchema" /> -->
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="编辑" />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="健康档案" />
        <!-- <ElButton circle :icon="iconAssets" @click="action('assets', row)" title="打标资产" /> -->
      </template>
    </Table>
  </ContentWrap>
  <Chat
    v-if="actionType == 'see'"
    :id="tableObject.currentRow.id"
    ref="flse"
    style="z-index: 9999999"
  />

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <!-- <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    /> -->

    <template #footer>
      <ElButton v-if="actionType == 'edit'" type="primary" :loading="loading" @click="save()">
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
